package com.waiting.java8.feature;

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

/**
 * @Description 方法引用
 * @Author bjweitingting
 * @Date 2018/10/10
 **/
public class FunctionReferTest {
    public static void main(String[] args) {
        List<String> al = Arrays.asList("a", "b", "c", "d");
//        //调用构造函数
//        al.forEach(AcceptMethod::new);
//        //实例方法引用
//        AcceptMethod acceptMethod = new AcceptMethod();
//        al.forEach((x) -> acceptMethod.print(x));
//        //类的实例方法引用，编译失败
////        al.forEach(AcceptMethod::print);
//        List<User2> list = new LinkedList<>();
//        list.add(new User2(18));
//        list.add(new User2(20));
//        list.sort(User2::sort);
        //java8之前的写法,编译该文件时，会产生一个继承了Consumer的类
        al.forEach(new Consumer<String>() {
            @Override
            public void accept(String s) {
                System.out.println("java8之前的写法");
                System.out.println(s);
            }
        });
        //lambda表达式
        al.forEach(item -> {
            System.out.println("lambda表达式的写法");
            System.out.println(item);
        });
        //类的静态方法引用，最终和lambda一样，是创建一个接口的实例，但是
        al.forEach(AcceptMethod::printValur);
        al.forEach(item -> AcceptMethod.printValur(item));
    }

    public void bar() {
        System.out.println("方法引用，bar");
    }
}

class AcceptMethod {

    private String var;

    AcceptMethod() {

    }

    AcceptMethod(String var) {
        this.var = var;
        System.out.println(var);
    }

    public static void printValur(String str) {
        System.out.println("print value : " + str);
    }

    public void print(String str) {
        System.out.println("print value : " + str);
    }
}

class User2 {
    String name;
    Integer age;

    User2() {

    }

    User2(String name) {
        this.name = name;
    }

    User2(Integer age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public int sort(User2 user) {
        return this.getAge() - user.getAge();
    }
}